package com.baoyouqun.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baoyouqun.domain.VO.PostTypeDTO;
import com.baoyouqun.entity.UserFollowPostType;
import com.baoyouqun.mapper.UserFollowPostTypeMapper;
import com.baoyouqun.service.SystemConfigService;
import com.baoyouqun.service.UserFollowPostTypeService;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
public class UserFollowPostTypeServiceImpl extends ServiceImpl<UserFollowPostTypeMapper, UserFollowPostType> implements UserFollowPostTypeService {

    @Resource
    private SystemConfigService systemConfigService;

    @Resource
    private UserFollowPostTypeMapper followPostTypeMapper;

    @Override
    public List<String> getByUserId(String userId) {
        List<UserFollowPostType> followList = list(new LambdaQueryWrapper<UserFollowPostType>()
                .eq(UserFollowPostType::getUserId, userId)
        );
        if (followList.isEmpty()) {
            return new ArrayList<>();
        }
        return followList.stream()
                .filter(Objects::nonNull)
                .map(UserFollowPostType::getPostTypeTitle)
                .filter(StringUtils::isNotBlank)
                .collect(Collectors.toList());
    }


    @Override
    public List<PostTypeDTO.PostTypeSonDTO> getUserFollowPostTypes(String userId) {
        // 1. 获取用户关注的所有类型标题
        List<UserFollowPostType> followList = list(new LambdaQueryWrapper<UserFollowPostType>()
                .eq(UserFollowPostType::getUserId, userId)
        );
        if (followList.isEmpty()) {
            // 返回默认分类：资源、市场、资金、人脉
            List<PostTypeDTO.PostTypeSonDTO> defaultList = new ArrayList<>();
            String[] defaultTitles = {"资源", "市场", "资金", "人脉"};

            for (String title : defaultTitles) {
                PostTypeDTO.PostTypeSonDTO defaultSonDTO = new PostTypeDTO.PostTypeSonDTO();
                defaultSonDTO.setTitle(title);
                defaultSonDTO.setCount(0); // 默认数量设为0（可根据业务调整）
                // 子列表默认是空ArrayList，无需额外设置
                defaultList.add(defaultSonDTO);
            }
            return defaultList;
        }
        List<String> followTitles = followList.stream()
                .map(UserFollowPostType::getPostTypeTitle)
                .collect(Collectors.toList());

        // 2. 获取所有帖子类型配置（单层结构）
        PostTypeDTO postTypeDTO = systemConfigService.getPostType();
        List<PostTypeDTO.PostTypeSonDTO> allTypeList = postTypeDTO.getList();

        // 3. 筛选出用户关注的类型（仅匹配单层标题）
        return allTypeList.stream()
                .filter(type -> followTitles.contains(type.getTitle()))
                .collect(Collectors.toList());
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void setUserFollowPostTypes(String userId, List<String> followTitles) {
        // 1. 先删除用户已有的关注
        LambdaQueryWrapper<UserFollowPostType> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserFollowPostType::getUserId, userId);
        remove(queryWrapper);

        if (followTitles == null || followTitles.isEmpty()) {
            return;
        }

        // 2. 获取所有帖子类型配置，校验标题有效性
        PostTypeDTO postTypeDTO = systemConfigService.getPostType();
        List<String> validTitles = postTypeDTO.getList().stream()
                .map(PostTypeDTO.PostTypeSonDTO::getTitle)
                .collect(Collectors.toList());

        // 3. 批量插入新的关注关系（生成String类型主键）
        List<UserFollowPostType> insertList = followTitles.stream()
                .filter(validTitles::contains) // 只保留有效标题
                .map(title -> {
                    UserFollowPostType entity = new UserFollowPostType();
                    entity.setId(UUID.randomUUID().toString().replace("-", "")); // 生成String主键
                    entity.setUserId(userId);
                    entity.setPostTypeTitle(title);
                    entity.setCreateTime(LocalDateTime.now());
                    return entity;
                })
                .collect(Collectors.toList());

        if (!insertList.isEmpty()) {
            saveBatch(insertList);
        }
    }

}